﻿RequestsApp.controller('AddCtrl', ['$scope', '$rootScope', '$location', 'SharePointJSOMService', '$log', function ($scope, $rootScope, $location, SharePointJSOMService, $log) {

    $scope.Request = new Request();
    $scope.FieldProperties = {};
    $scope.submitButtonText = 'Add request';
    //#region get taxonomy field properties
    SharePointJSOMService.getRequestTaxonomyFieldsProperties()
    .then(
    function (properties) {
        $scope.FieldProperties = properties;
    },
    function (err) {
        $log.error(JSON.stringify(err));
        noty({ text: JSON.stringify(err), type: 'error' });
    });
    //#endregion

    //#region add task
    $scope.submitRequest = function ($event) {
        addRequest($event);
    };

    var addRequest = function ($event) {
        $event.preventDefault();

        if (!$scope.mainForm.$valid) {
            return;
        }

        SharePointJSOMService.addRequest($scope.Request)
        .then(
        function (id) {
            $scope.Request.Id = id;
            $location.path("/home").replace();
            noty({ text: 'Request succesfully added', type: 'success' });
        },
        function (err) {
            $log.error(err);
            noty({ text: JSON.stringify(err), type: 'error' });
        });
    };

    $scope.cancel = function ($event) {
        $event.preventDefault();
        $location.path("/home");
    };
    //#endregion
}]);